package mux

import (
	"expvar"
	"net/http"
	"net/http/pprof"

	"gitee.com/go-wena/app/internal/redis"
	"gitee.com/go-wena/app/internal/sql"
	"gitee.com/go-wena/app/internal/sys"
	"gitee.com/go-wena/env"
	"github.com/go-chi/chi"
)

func (m *Mux) profiler(router chi.Router) {
	if env.IsFalse("router.profiler.enabled") {
		return
	}

	if !env.IsFalse("router.profiler.vars") {
		router.Method(http.MethodGet, "/debug/vars", expvar.Handler())
	}

	if !env.IsFalse("router.profiler.pprof") {
		router.MethodFunc(http.MethodGet, "/debug/pprof/cmdline", pprof.Cmdline)
		router.MethodFunc(http.MethodGet, "/debug/pprof/profile", pprof.Profile)
		router.MethodFunc(http.MethodGet, "/debug/pprof/symbol", pprof.Symbol)
		router.MethodFunc(http.MethodGet, "/debug/pprof/trace", pprof.Trace)
	}

	if !env.IsFalse("router.profiler.sys") {
		router.Method(http.MethodGet, "/debug/stats/sys", m.wrap(func(c *Context) {
			c.JSON(sys.GetStatus())
		}))
	}

	if !env.IsFalse("router.profiler.sql") {
		router.Method(http.MethodGet, "/debug/stats/sql", m.wrap(func(c *Context) {
			c.JSON(sql.GetStats())
		}))
		router.Method(http.MethodGet, "/debug/stats/sql/ping", m.wrap(func(c *Context) {
			if err := sql.Ping(c.Context()); err != nil {
				c.Error(err.Error())
			} else {
				c.Plain("OK")
			}
		}))
	}

	if !env.IsFalse("router.profiler.redis") {
		router.Method(http.MethodGet, "/debug/stats/redis", m.wrap(func(c *Context) {
			c.JSON(redis.GetStats())
		}))
		router.Method(http.MethodGet, "/debug/stats/redis/ping", m.wrap(func(c *Context) {
			if err := redis.Ping(c.Context()); err != nil {
				c.Error(err.Error())
			} else {
				c.Plain("OK")
			}
		}))
	}
}
